package com.zretc.demojparedis.service.impl;

import com.zretc.demojparedis.commons.LoginBean;
import com.zretc.demojparedis.dao.AuthRedis;
import com.zretc.demojparedis.dao.UsersDao;
import com.zretc.demojparedis.entity.Users;
import com.zretc.demojparedis.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * Created by admin on 2020/7/18.
 */
@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersDao usersDao;

    @Autowired
    private AuthRedis authRedis;

    @Override
    public LoginBean getUsersByNameAndPwd(String userName, String userPwd) {

        Users user =  usersDao.findByUserNameAndUserPwd(userName,userPwd);
        LoginBean loginBean = new LoginBean();
        if (user!=null)
        {
            //System.currentTimeMillis() + new Random().nextInt(999999999)
            //uuid
            String token = UUID.randomUUID().toString();

            loginBean.setCode(200);
            loginBean.setMsg("登录成功!");
            loginBean.setUser(user);
            loginBean.setToken(token);

            authRedis.set(token,userName);

        }
        else
        {
            loginBean.setCode(401);
            loginBean.setMsg("登录失败!");
        }

        return loginBean;
    }

    /**
     * 登出，注销
     * @return
     */
    public String logout(String token) {
        Boolean flag = authRedis.delete(token);
        if (!flag) {
            return "注销失败，请检查是否登录！";
        }
        return "注销成功！";
    }
}
